/**
 * 常用工具方法
 */
import Cookies from "js-cookie";

export default {
    ENV: process.env.NODE_ENV,
    MSG: process.env.VUE_APP_MSG,
    API_PREFIX: process.env.VUE_APP_BASE_API,
    token: "Authorization",
    logout: false,
    lsPut(key, val) {
        window.localStorage.setItem(key, JSON.stringify(val));
    },
    lsGet(key, defaultVal) {
        return JSON.parse(window.localStorage.getItem(key) || defaultVal)
    },
    setToken(res) {
        this.logout = false;
        const now = Date.now();
        if (res && res.data && res.data.authorization && res.data.jwtTTLRefresh) {
            window.localStorage.setItem(this.token, JSON.stringify({
                token: res.data.authorization,
                tokenExpireTime: now + res.data.jwtTTLRefresh
            }));
        }
    },
    getToken() {
        let tokenObj = window.localStorage.getItem(this.token);
        tokenObj = tokenObj ? JSON.parse(tokenObj) : {};
        return tokenObj;
    },
    clearToken() {
        this.logout = true;
        window.localStorage.removeItem(this.token);
    },
    cookieSet(key, val, expires) {
        if (expires) {
            Cookies.set(key, val, {expires});
        } else {
            Cookies.set(key, val);
        }
    },
    cookieGet(key) {
        return Cookies.get(key);
    },
    /**
     * 检查对象的真实类型
     */
    checkType(obj) {
        return Object.prototype.toString.call(obj).slice(8, -1);
    },
    /**
     * 深拷贝对象
     * @param obj 被拷贝的对象
     * @param containsPrototype 是否拷贝父级或原型的属性
     */
    clone(obj, containsPrototype = true) {
        let result, objType = this.checkType(obj);
        if (objType === "Object") {
            result = {}
        } else if (objType === "Array") {
            result = []
        } else {
            return obj;
        }
        for (let property in obj) {
            if (containsPrototype || obj.hasOwnProperty(property)) {
                let val = obj[property];
                if (this.checkType(val) === "Object" || this.checkType(val) === "Array") {
                    result[property] = this.clone(val);
                }
                result[property] = val;
            }
        }
        return result;
    },
    /**
     *  合并用户配置并返回新对象
     * @param conf  用户配置
     * @param defaultConf 默认配置
     */
    merge(conf, defaultConf) {
        let result = this.clone(conf);
        for (let property in defaultConf) {
            if (this.checkType(result[property]) === "Undefined") {
                result[property] = this.clone(defaultConf[property]);
            } else if (this.checkType(result[property]) === "Object") {
                result[property] = this.merge(result[property], defaultConf[property]);
            }
        }
        return result;
    }
}
